<?php

namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Libraries\vendor\DocParser;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\DB;
use ReflectionClass;
use ReflectionMethod;
class AdminController extends Controller{
	public $menu_list=[];
	public $menu_option_list=[];
    public $admin = [];

	public function __construct(){
        $this->admin = session('admin');
      
        $this->admin['rights'] = $this->admin['rights'];
        $this->menu_list = $this->get_all_menu_list(1);
        $this->menu_option_list = $this->get_all_menu_list(0);


        if( empty($this->admin['id']) ){
            header("location:/auth/login");
            exit();
        }

        view()->share('admin_menu_list',$this->menu_list);
        view()->share('admin_option_list',$this->menu_option_list);
        view()->share('admin',$this->admin);
        
        $rights = DB::table('admindata')->where('id',$this->admin['id'])->first(['rights']);
        view()->share('admin_rights', explode('|',$rights->rights));
        #dd($this->menu_list,$this->menu_option_list,$rights);
        $last_url = Cache::get('admin:menu:key:'.$this->admin['id']);
        #dd($last_url);
        last_url($this->admin['id']);
        view()->share('last_url',$last_url);
	}

    /**
     * 后台通用导出
     * @author liuchang
     * @param  Builder $builder
     * @param  Array   $keys
     * @param  String  $filename
     */
    public function _export($builder, $keys='', $filename){
        if(!request()->_export){ return false; }
        $list = $builder->select($keys)->take(500)->get()->toArray(); 
        die(make_csv([array_merge([$keys], $list), $filename]));
    }

	/**
     * 获取权限菜单项
     * @param $type 0获取权限，1获取菜单
     * @author wudi
     */
    public function get_all_menu_list($type){
        $controllers = [];
        $handle = opendir(app_path().DIRECTORY_SEPARATOR.'Http'.DIRECTORY_SEPARATOR.'Controllers'.DIRECTORY_SEPARATOR.'Admin');
        if($handle){
            while(($file=readdir($handle))!==false){
                if($file=='.' || $file=='..') continue;
                $controllers[] = str_replace('.php', '', $file);
            }
        }

        $power =[];
        foreach($controllers as $ctrl){
            //权限开始
            $classname = "return \App\Http\Controllers\Admin\\".$ctrl."::class;";
            $reflection = new ReflectionClass (eval($classname));
            //通过反射获取类的注释
            $doc = $reflection->getDocComment();
            $controller_name = $this->get_controller_name($reflection->name);
            //解析类的注释头
            $parse_doc =  (new DocParser())->parse( $doc );
            if(empty($parse_doc) || empty($parse_doc['menu_cat']) ) continue;
            $menu_cat = $parse_doc['menu_cat'];

            if($type === 1){
                if(empty($power[$menu_cat]['icon'])){ // icon
                    $power[$menu_cat]['icon'] = !empty($parse_doc['icon']) ? $parse_doc['icon'] : '';
                }
                if(empty($power[$menu_cat]['sort'])){ // sort
                    $power[$menu_cat]['sort'] = !empty($parse_doc['sort']) ? $parse_doc['sort'] : 0;
                }
            }

            $arguments = $defaults = [];
            $methods = $reflection->getMethods(ReflectionMethod::IS_PUBLIC + ReflectionMethod::IS_PROTECTED + ReflectionMethod::IS_PRIVATE);
            foreach ($methods as $method) {
                //获取方法的注释
                $doc = $method->getDocComment();
                $parse_method = (new DocParser())->parse( $doc );
                $function = $method->name;

                $lines_arr = [];
                foreach ($parse_method as $k=>$v) {
                    $haystack = ['menu','menu_cat'];
                    if($type === 0){ $haystack[] = 'name'; }
                    if($type === 1){ $haystack[] = 'icon';$haystack[] = 'sort'; }

                    if( in_array($k, $haystack) ){
                        $lines_arr[$k] = $v;
                        $lines_arr['function'] = $function;
                    }
                }


                if(isset($lines_arr['menu']) || isset($lines_arr['name'])){
                    $menu_cat = !empty($lines_arr['menu_cat']) ? trim($lines_arr['menu_cat']) : $menu_cat;
                    if($type ===1){
                        $power[$menu_cat]['list'][$controller_name.'.'.$function] = $lines_arr['menu'] ?? $lines_arr['name'];
                        $power[$menu_cat]['icon'] = !empty($power[$menu_cat]['icon']) ? $power[$menu_cat]['icon'] : (!empty($lines_arr['icon']) ? $lines_arr['icon'] : '');
                        $power[$menu_cat]['sort'] = !empty($power[$menu_cat]['sort']) ? $power[$menu_cat]['sort'] : (!empty($lines_arr['sort']) ? $lines_arr['sort'] : 0);
                    }else{
                        $power[$menu_cat][$controller_name.'.'.$function] = $lines_arr['menu'] ?? $lines_arr['name'];
                    }
                }
            }
        }

        if($type === 1){ sort_array_by_field($power, 'sort'); }
        return ($power);
    }

    public function get_comment($comment){
        if (preg_match ( '#^/\*\*(.*)\*/#s', $doc, $comment ) !== false){
            $comment = $comment[1];
            if(preg_match_all ( '#^\s*\*(.*)#m', $comment, $lines ) !== false){
                $lines = $lines[1];
                foreach ($lines as $r) {
                    $r = trim($r);
                    if(stripos($r, '@')!==false){
                        print_r(explode(' ', $r));
                    }
                }
            }
        }
    }

    public function get_controller_name($name){
        $name = explode('\\', $name);
        return end($name);
    }
}